<?php

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use utils\out;
/**菜单首页*/
$app->get('/menu', function (Application $app) {

    // 获取推荐
    $sql = "SELECT id, title, thumbnail, createdAt, modifiedAt, isDeleted, status, rank, viewCount, praiseCount FROM t_menu WHERE isDeleted = 0 AND status = 2 AND isRecommend=1 Limit 1";
    $rec = $app['db']->fetchAssoc($sql);
    if(!$rec) {
        $rec = new stdClass();
        $rec->id = 0;
    }
//	$app['twig']->render('menu_list.html', array("rec"=>$rec, "recstr"=>json_encode($rec)));
    return $app->json(['status'=>'ok','arr'=>$rec]);
});

/**菜单列表*/
$app->get('/menu/list', function (Application $app, Request $request) {
	$limit = 20;
	$page = $request->get('page');
	if (!$page) {
        $page = 1;
    }
	
	$start = ($page - 1) * $limit;
	$keyword = $request->get('keyword');

	$sql = "SELECT id, title, thumbnail, createdAt, modifiedAt, isDeleted, status, rank, viewCount, praiseCount,main FROM t_menu WHERE isDeleted = 0 AND status = 2 ";
	if($keyword) {
	    $sql = $sql. "AND (title like '%". $keyword . "%' OR main like '%". $keyword . "%') ";
	}

	$sql = $sql. "ORDER BY createdAt DESC LIMIT $start, $limit";

	$data = $app['db']->fetchAll($sql);

//	$result = array('success'=>true, "result"=>array('items'=>$data));
//	return $app->json($result);

	$result = array('status'=>'ok', "arr"=>$data);
	return $app->json($result);
});

/**菜单详情*/
$app->get('/menu/{id}', function (Application $app, $id) {
	$sql = "SELECT * FROM t_menu WHERE isDeleted = 0 AND id = ?";
	$data = $app['db']->fetchAssoc($sql, array((int) $id));
	
	if($data == false){
		$result = array('status'=>'ok', "arr"=>[]);
		return $app->json($result);
	}
	
	$data['mainArray'] = explode(',', $data['main']);
	$data['assistArray'] = explode(',', $data['assist']);

//	return $app['twig']->render('menu_detail.html', array('result'=>$data));

	$result = array('status'=>'ok', "arr"=>$data);
	return $app->json($result);
});

/**增加浏览量*/
$app->post('/menu/viewcount/{id}', function (Application $app, $id) {
	
	$sql = "UPDATE t_menu SET viewCount=viewCount+1 WHERE id=$id";
	$data = $app['db']->executeUpdate($sql);
		
	$result = array('status'=>'ok', "result"=>"ok");
	return $app->json($result);
});